package com.ludaxu.zhbj.view;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ludaxu.zhbj.R;

public class RefreshListView extends ListView implements OnScrollListener,
		android.widget.AdapterView.OnItemClickListener {
	private View mHeaderView;
	private int startY = -1;// 滑动起点的Y坐标
	private int mHeaderViewHeight;
	private static final int STATE_PULL_REFRESH = 0;// 下拉刷新
	private static final int STATE_RELEASE_REFRESH = 1;// 松开刷新
	private static final int STATE_REFRESHING = 2;// 正在刷新
	private int mCurrentState = STATE_PULL_REFRESH;// 当前状态,默认为下拉刷新
	private TextView tvTitle;
	private TextView tvTime;
	private ImageView ivArrow;
	private ProgressBar pbProgress;
	private RotateAnimation rotateUp;
	private RotateAnimation rotateDown;

	/**
	 * 初始化头布局
	 */
	private void initHeaderView() {
		mHeaderView = View.inflate(getContext(), R.layout.refresh_header, null);

		// 先加的headview显示在上面
		this.addHeaderView(mHeaderView);

		tvTitle = (TextView) mHeaderView.findViewById(R.id.tv_title);
		tvTime = (TextView) mHeaderView.findViewById(R.id.tv_time);
		ivArrow = (ImageView) mHeaderView.findViewById(R.id.iv_arr);
		pbProgress = (ProgressBar) mHeaderView.findViewById(R.id.pb_progress);

		// 测量mHeaderVIew
		mHeaderView.measure(0, 0);
		mHeaderViewHeight = mHeaderView.getMeasuredHeight();
		mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
		// 初始化动画
		initArrowAnim();
		tvTime.setText("最后刷新时间:" + getCurrentTime());

	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startY = (int) ev.getRawY();

			break;
		case MotionEvent.ACTION_MOVE:
			if (startY == -1) {// 有时候按下的时候会拿不到y的值,这个时判断,确保拿到y的值
				startY = (int) ev.getRawY();
				Toast.makeText(getContext(), "startY 重新拿值", 0).show();
			}
			// 正在刷新时,不做处理
			if (mCurrentState == STATE_REFRESHING) {
				break;
			}

			int endY = (int) ev.getRawY();
			int dy = endY - startY;// 移动的偏移量
			// dy是大于0,而且listview显示第一个位置时才下拉刷新
			if (dy > 0 && getFirstVisiblePosition() == 0) {
				// 计算padding
				int padding = dy - mHeaderViewHeight;
				// 设置padding
				mHeaderView.setPadding(0, padding, 0, 0);
				if (padding > 0 && mCurrentState != STATE_RELEASE_REFRESH) {
					mCurrentState = STATE_RELEASE_REFRESH;// 当前状态改变为松开刷新
					refreshState();

				} else if (padding <= 0 && mCurrentState != STATE_PULL_REFRESH) {
					mCurrentState = STATE_PULL_REFRESH;// 当前状态改为下拉刷新
					refreshState();
				}
				return true;
			}

			break;
		case MotionEvent.ACTION_UP:
			startY = -1;// 重置startY
			if (mCurrentState == STATE_RELEASE_REFRESH) {
				mCurrentState = STATE_REFRESHING;
				mHeaderView.setPadding(0, 0, 0, 0);// 显示
				refreshState();
			} else if (mCurrentState == STATE_PULL_REFRESH) {
				mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
			}
			break;

		default:
			break;
		}
		return super.onTouchEvent(ev);
	}

	/**
	 * 刷新下拉控件的布局
	 */
	private void refreshState() {
		switch (mCurrentState) {
		// 下拉刷新
		case STATE_PULL_REFRESH:
			tvTitle.setText("下拉刷新");
			ivArrow.setVisibility(View.VISIBLE);
			pbProgress.setVisibility(View.INVISIBLE);
			ivArrow.startAnimation(rotateDown);
			break;
		// 松开刷新
		case STATE_RELEASE_REFRESH:
			tvTitle.setText("松开刷新");
			ivArrow.setVisibility(View.VISIBLE);
			pbProgress.setVisibility(View.INVISIBLE);
			ivArrow.startAnimation(rotateUp);

			break;
		// 正在刷新
		case STATE_REFRESHING:
			tvTitle.setText("正在刷新...");
			// 必须先清除动画才能隐藏
			ivArrow.clearAnimation();
			ivArrow.setVisibility(View.INVISIBLE);
			pbProgress.setVisibility(View.VISIBLE);

			if (mListener != null) {
				mListener.onRefresh();
			}

			break;

		default:
			break;
		}

	}

	@SuppressLint("NewApi")
	public RefreshListView(Context context, AttributeSet attrs,
			int defStyleAttr, int defStyleRes) {
		super(context, attrs, defStyleAttr, defStyleRes);
		initHeaderView();
		initFooterView();
	}

	public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initHeaderView();
		initFooterView();
	}

	public RefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initHeaderView();
		initFooterView();
	}

	public RefreshListView(Context context) {
		super(context);
		initHeaderView();
		initFooterView();
	}

	private void initArrowAnim() {
		rotateUp = new RotateAnimation(0, -180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		rotateUp.setDuration(200);
		rotateUp.setFillAfter(true);
		rotateDown = new RotateAnimation(-180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		rotateDown.setDuration(200);
		rotateDown.setFillAfter(true);
	}

	OnRefreshListener mListener;
	private View mFooterView;
	private int mFooterViewHeight;

	public void setOnReFreshListener(OnRefreshListener listener) {

		mListener = listener;

	}

	public interface OnRefreshListener {

		public void onRefresh();// 刷新

		public void onLoadMore();// 加载更多数据

	}

	/**
	 * 收起下拉刷新的控件
	 */
	public void OnRefreshComplete() {
		if (isLoadingMore) {
			// 隐藏角布局
			mFooterView.setPadding(0, -mFooterViewHeight, 0, 0);
			isLoadingMore = false;
		} else {
			mCurrentState = STATE_PULL_REFRESH;
			tvTitle.setText("下拉刷新");
			ivArrow.setVisibility(View.VISIBLE);
			pbProgress.setVisibility(View.INVISIBLE);

			mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
			tvTime.setText("最后刷新时间:" + getCurrentTime());
		}

	}

	/**
	 * 获取当前时间
	 */
	public String getCurrentTime() {
		// 其中HH是24小时.hh是12小时制.
		// MM表示月份从1开始,小写从0开始
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(new Date());

	}

	/**
	 * 初始化角布局
	 */
	private void initFooterView() {
		mFooterView = View.inflate(getContext(),
				R.layout.refresh_listview_footer, null);
		this.addFooterView(mFooterView);
		mFooterView.measure(0, 0);
		mFooterViewHeight = mFooterView.getMeasuredHeight();
		mFooterView.setPadding(0, -mFooterViewHeight, 0, 0);
		this.setOnScrollListener(this);

	}

	private boolean isLoadingMore;

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == SCROLL_STATE_IDLE
				|| scrollState == SCROLL_STATE_FLING) {
			if (getLastVisiblePosition() == getCount() - 1 && !isLoadingMore) {// 滑动到最后
				System.out.println("到底了........");
				mFooterView.setPadding(0, 0, 0, 0);
				// 改变listview的显示位置
				setSelection(getCount() - 1);
				isLoadingMore = true;
				if (mListener != null) {
					mListener.onLoadMore();
				}
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub

	}

	OnItemClickListener mItemClickListener;

	@Override
	public void setOnItemClickListener(
			android.widget.AdapterView.OnItemClickListener listener) {
		// TODO Auto-generated method stub
		super.setOnItemClickListener(this);

		mItemClickListener = listener;

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (mItemClickListener != null) {
			mItemClickListener.onItemClick(parent, view, position
					- getHeaderViewsCount(), id);

		}
	}

}
